package com.gxljc.bear.crawler.util;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.client.HTableInterface;
import org.apache.hadoop.hbase.client.HTablePool;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.util.PoolMap;
import org.apache.log4j.Logger;

import java.io.IOException;

public class HbaseTablePool {
	private static HTablePool pool;
	private static Logger LOG = Logger.getLogger(HbaseTablePool.class);

	public static HTablePool getHTablePool(Configuration conf) {
		if (pool == null) {
			synchronized (HTablePool.class) {
				if (pool == null) {
					pool = new HTablePool(conf, 10,
							PoolMap.PoolType.ThreadLocal);
				}
			}
		}
		return pool;
	}

	@SuppressWarnings("deprecation")
	public static void export(String table, String rowKey, String family,
			String qualifier, String data) {
		pool = getHTablePool(HBaseConfiguration.create());
		Put put = new Put(rowKey.getBytes());
		put.add(family.getBytes(), qualifier.getBytes(), data.getBytes());
		HTableInterface hTable = pool.getTable(table);
		try {
			hTable.put(put);
		} catch (IOException e) {
			LOG.error("hTable.put error", e);
		} finally {
			if (hTable != null)
				try {
					pool.putTable(hTable);
				} catch (IOException e) {
					LOG.error("pool error", e);
				}
		}
	}

}
